<template>
  <div
    class="drag-drop-box"
    ondragstart="return false"
    :style="{ left: translate.x + 'px', top: translate.y + 'px' }"
    @mousedown="mousedown"
  >
    <slot name="default" />
  </div>
</template>

<script lang="ts" setup>
import { ref, withDefaults } from 'vue'

const props = withDefaults(defineProps<{
  top?: string,
  left?: string,
}>(), {
  top: '0',
  left: '0'
})

const emits = defineEmits(['update:top', 'update:left'])

onMounted(() => {
  if (props.top) translate.value.y = Number(props.top.replace('px', ''))
  if (props.left) translate.value.x = Number(props.left.replace('px', ''))
})

// region TODO 偏移信息
// 记录按下时的坐标点
let downPoint: any = null
// 记录按下时的偏移
let downRefPoint: any = null
// 偏移
const translate = ref({ x: 0, y: 0 })
// endregion

// region TODO 移动
const mousedown = (e: any) => {
  downPoint = { x: e.x, y: e.y }
  downRefPoint = JSON.parse(JSON.stringify(translate.value))
  document.addEventListener('mousemove', mousemove)
  document.addEventListener('mouseup', mouseup)
}
const mousemove = (e: any) => {
  const offsetPoint = {
    x: e.x - downPoint.x,
    y: e.y - downPoint.y
  }
  translate.value.x = downRefPoint.x + offsetPoint.x
  translate.value.y = downRefPoint.y + offsetPoint.y
}
const mouseup = () => {
  document.removeEventListener('mousemove', mousemove)
  document.removeEventListener('mouseup', mouseup)
  emits('update:top', translate.value.y + 'px')
  emits('update:left', translate.value.x + 'px')
}
// endregion

</script>

<style lang="scss" scoped>
.drag-drop-box {
  position: absolute;
}
</style>
